package agriculture.service.imp;

import agriculture.bean.Order;
import agriculture.bean.OrderDetail;
import agriculture.config.RabbitMQConfig;
import agriculture.dto.OrderRequest;
import agriculture.dto.StockDTO;
import agriculture.dto.UpdateReceiverRequest;
import agriculture.mapper.OrderDetailMapper;
import agriculture.mapper.OrderMapper;
import agriculture.service.OrderService;
import agriculture.system.api.model.OrderPaidMessage;
import agriculture.util.OrderIdGenerator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrderServiceImp implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
//    @Resource
//    private ProductFeignClient productFeignClient;

    @Override
    public Order createOrder(OrderRequest orderRequest) {
        Order order = new Order();
        order.setOrderNumber(OrderIdGenerator.generateOrderId()); //使用雪花算法来生成订单号
        order.setUserId(orderRequest.getUserId());
        order.setProductId(orderRequest.getProductId());
        order.setProductName(orderRequest.getProductName());
        order.setCreateTime(LocalDateTime.now());
        order.setTotalAmount(orderRequest.getTotalAmount());
        order.setProductImg(orderRequest.getProductImg());
        order.setStatus("0"); //未支付状态，1为支付状态,2为取消支付


        orderMapper.insert(order);
        // 发送延迟消息（15分钟后自动取消订单）
        rabbitTemplate.convertAndSend(
                RabbitMQConfig.EXCHANGE_NAME, //交换机名称
                "order.delay",  // ✅ 必须和延迟队列绑定用的一致
                order.getOrderNumber() //消息体
        );
        return order;
    }

    /**
     * 根据用户Id获取该用户的所有订单信息
     * @param userId
     * @return
     */
    @Override
    public List<Order> selectOrderAllByUserId(Long userId) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        return orderMapper.selectList(queryWrapper);
    }

    /**
     * 更新订单的状态
     * @param orderNumber
     * @param status
     */
    @Override
    public void updateOrderStatus(String orderNumber, String status,LocalDateTime payTime) {
          QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
          queryWrapper.eq("order_number",orderNumber);
          Order order = orderMapper.selectOne(queryWrapper);

          if(order!=null){
              order.setStatus(status);
              order.setPaymentTime(payTime);
              orderMapper.updateById(order);
              System.out.println("更新主表状态已经支付时间成功！");
          }
    }

    /**
     * 添加订单详情表
     * @param orderNumber
     */
    @Override
    public void insertOrderDetails(String orderNumber,int quantity,String paymentMethod) {
        // 1. 根据订单编号查询主订单
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_number",orderNumber);
        Order order = orderMapper.selectOne(queryWrapper);

        if(order!=null){
            // 2. 创建订单详情对象
            OrderDetail detail = new OrderDetail();
            detail.setOrderId(order.getId());
            detail.setUserId(order.getUserId());
            detail.setOrderNumber(order.getOrderNumber());
            detail.setProductId(order.getProductId());
            detail.setProductName(order.getProductName());
//            detail.setProductSku("SKU001"); // 这里如果有具体 SKU 编号建议从前端传过来或从商品表查询
            detail.setPrice(order.getTotalAmount()); // 单价
            detail.setQuantity(quantity); // 数量
            /**
             * new BigDecimal(quantity) 是将整数类型转换为 BigDecimal
             * multiply 是乘的运算， .multiply(...)
             * 这是 BigDecimal 类中的乘法方法
             * 会返回：单价 × 数量 = 总价
             */
            detail.setSubtotal(order.getTotalAmount().multiply(new BigDecimal(quantity)));//总价
            detail.setReceiverName(order.getReceiverName());
            detail.setReceiverPhone(order.getReceiverPhone());
            detail.setReceiverAddress(order.getReceiverAddress());
            detail.setShippingCost(new BigDecimal("0.00"));
            detail.setPaymentMethod(paymentMethod);

            // 3. 插入订单详情记录
            orderDetailMapper.insert(detail);
            System.out.println("订单详情记录插入成功！");
        }
    }

    /**
     * 增加收货人信息
     * @param orderNumber
     * @param updateReceiverRequest
     */
    @Override
    public boolean updateOrderInfo(String orderNumber, UpdateReceiverRequest updateReceiverRequest) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_number",orderNumber);
        Order order = orderMapper.selectOne(queryWrapper);

        //更新收货人信息
        if(order!=null){
            order.setReceiverName(updateReceiverRequest.getReceiverName());
            order.setReceiverPhone(updateReceiverRequest.getReceiverPhone());
            order.setReceiverAddress(updateReceiverRequest.getReceiverAddress());

            orderMapper.updateById(order);
            return true;
        }

        return false;
    }

    /**
     * 根据订单的ID去获取对应的订单详细信息（订单主表）
     * @param orderNumber
     * @return
     */
    @Override
    public Order getOrderDetailByOrderNumber(String orderNumber) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_number",orderNumber);
        System.out.println("查询订单主表信息成功");
        return orderMapper.selectOne(queryWrapper);
    }

    /**
     * 根据订单的ID去获取商品的ID
     * @param orderNumber
     * @return
     */
    @Override
    public Long getProductIdByOrderNumber(String orderNumber) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_number",orderNumber).select("product_id");
        Order order = orderMapper.selectOne(queryWrapper);
        return order != null ?order.getProductId(): null;
    }

    @Override
    @Transactional
    public void handleOrderPaid(OrderPaidMessage message) {
        // 1. 更新订单状态
        updateOrderStatus(message.getOrderNumber(), "1", message.getPayTime());

        // 2. 插入订单详情
        insertOrderDetails(message.getOrderNumber(), message.getQuantity(), message.getPaymentMethod());

        // 3. 获取商品ID
        Long productId = getProductIdByOrderNumber(message.getOrderNumber());
        if (productId == null) {
            throw new RuntimeException("根据订单号查询商品ID失败！");
        }

        // 4. 调用商品服务扣库存
        StockDTO dto = new StockDTO();
        dto.setProductId(productId);
        dto.setQuantity(message.getQuantity());

//        //远程商品扣库存服务
//        boolean success = productFeignClient.decreaseStock(dto);
//        if (!success) {
//            throw new RuntimeException("远程扣减库存失败！");
//        }

        System.out.println("【订单服务】支付完成处理成功，订单号：" + message.getOrderNumber());
    }

}
